import { BaseMap } from "./map/BaseMap";
import { MapPlayer } from "./map/MapPlayer";
import { Maps } from "../../config/XlsxDef";
import { querySql } from "../../common/db";
import { ServerMain } from "../ServerMain";
import { SvrType } from "../../config/SvrCfg";

/**
 * Game服务器全局
 */
export const gameMain = _ as GameMain;
export class GameMain extends ServerMain {

    /** 总注册的玩家数量 */
    total: number;
    /** 服务器id */
    sid: number;
    /** 在线人数 */
    onlines = 0;
    /** 开服时间 */
    openTime: number;

    /** 暂时测试地图 */
    map: BaseMap

    players: MapPlayer[] = [];
    playerDic: { [pid: number]: MapPlayer } = {}

    async init() {
        (gameMain as any) = this;
        this.sid = this.app.svr.args.sid;
        this.openTime = Math.floor(new Date(this.app.svr.args.openTime).getTime() / 1000);

        this.app.miscCfg.onAddSvr = svr => {
            if (svr.type == SvrType.gate) {
                this.syncOnlines();
            }
        };
        setInterval(this.syncOnlines.bind(this), 30 * 1000);

        let res = await querySql("select count(*) from `player` where `sid` = ?", [this.sid]);
        this.total = res[0]["count(*)"];

        this.map = new BaseMap(Maps.start);
        this.map.start();
    }

    syncOnlines() {
        this.app.rpc(SvrType.gate).gate.main.setOnlines(this.sid, this.onlines);
    }


    addPlayer(player: MapPlayer) {
        if (this.playerDic[player.pid]) return;
        this.players.push(player);
        this.playerDic[player.pid] = player;
    }

    delPlayer(pid: number) {
        let player = this.playerDic[pid];
        if (!player) return;
        player.map && player.map.delPlayer(player.pid);
        this.players.splice(this.players.indexOf(player), 1);
        delete this.playerDic[pid];
    }
}